package com.qdlc.p2p.biz.service.user.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.user.AbstractResetPasswordStrategyService;
import com.qdlc.p2p.biz.service.user.ResetPasswordStepModel;
import com.qdlc.p2p.biz.util.UserReturnResult;
import com.qdlc.p2p.biz.util.ValidCodeSender;
import com.qdlc.p2p.common.constant.NoticeTplNid;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.common.util.ValidateUtil;
import com.qdlc.p2p.dal.dto.User;

@Service
public class ResetPasswordEmailStrategyImpl extends AbstractResetPasswordStrategyService {
	
	/**
	 * 第一步:
	 * 1. 验证邮箱、图形验证码
	 * 2. 发送邮箱验证码
	 * @param stepModel
	 * @return
	 */
	protected ReturnResult step1(ResetPasswordStepModel stepModel){
		
		//用户邮箱
		String email = stepModel.getKeyWorlds();
		//图形验证码
		String validCode = stepModel.getValidCode();
		
		//检测手机号码和图形验证码
		ReturnResult result = checkStep1(email, validCode);
		if(result.isError()){
			return result;
		}
		
		//发送短信验证码，进入到下一步
		User user = ((UserReturnResult)result).getUser();
        result = ValidCodeSender.newInstance().sendCodeByEmail(user, email, NoticeTplNid.NOTICE_GET_PWD_EMAIL);
		
		return result;
	} 
	
	/**
	 * 检测第一步参数: 检测手机号码和图形验证码
	 * @param email
	 * @param validCode
	 * @return
	 */
	private ReturnResult checkStep1(String email, String validCode){
		
		//检测手机号码
		if (StringUtils.isBlank(email)) {
			return new ReturnResult("邮箱不能为空!");
		}
		
		if (!ValidateUtil.isEmail(email)) {
			return new ReturnResult("邮箱格式错误!");
		}
		
		//检测验证码
		if (StringUtils.isBlank(validCode)) {
			return new ReturnResult(MessageUtil.getMessage("E30005"));
		}
		
		if (!ValidateUtil.checkValidCode(validCode)) {
			return new ReturnResult(MessageUtil.getMessage("E30006"));
		}
		
		//验证手机号码是否存在
		ReturnResult result = findUserByKeys(email);
		
		return result;
	}
	
	
	@Override
	protected ReturnResult step2CheckValidCode(User user, String code) {
		return ValidCodeSender.checkValidCode(user, code, NoticeTplNid.NOTICE_GET_PWD_EMAIL);
	}

	/**
	 * 获取用户信息
	 * @param email
	 * @return
	 */
	protected ReturnResult findUserByKeys(String email){
		User user = userDao.findObjByProperty("email", email);
		if(user == null){
			return new ReturnResult("该邮箱不存在!");
		}
		
		return new UserReturnResult(user);
	}
	
}
